import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from "rxjs";
import {AjaxResponse} from "../model/AjaxResponse";
import {share} from "rxjs/operators";

@Injectable({
    providedIn: 'root'
})
export class SecurityService {
    /**
     * 当前用户对应的项目权限列表
     */
    userProjectPermissionsResponse = {};

    user = {};

    constructor(private http: HttpClient) {
    }

    getUser(): Observable<AjaxResponse> {
        const cacheUser = this.user[0];
        if (!!cacheUser && !!cacheUser.data) {

            return new Observable(subscriber => {
                subscriber.next(cacheUser.data)
            })
        }
        if (!!cacheUser && cacheUser.observable) {
            return cacheUser.observable;
        }

        let userName$ = this.http.get<AjaxResponse>('api/security/user').pipe(share());
        this.user[0] = {
            observable: userName$
        };
        userName$.subscribe(rs => {
                delete this.user[0].observable;
                this.user[0].data = rs
            }
        )
        return userName$;

    }

    hasProjectPermissions(projectId: string, permission: string) {
        return false;
    }

    loadUserProjectPermissions(projectId: string): Observable<any> {
        const cacheData = this.userProjectPermissionsResponse[projectId];
        if (!!cacheData && !!cacheData.data) {
            return new Observable(subscriber => {
                subscriber.next(cacheData.data)
            })
        }

        /**
         * 如果订阅存在，则有请求未回来，直接重用即可
         */
        if (!!cacheData && cacheData.observable) {
            return cacheData.observable;
        }

        const observable$ = this.http.get(`api/security/project/${projectId}/permissions`).pipe(share());
        this.userProjectPermissionsResponse[projectId] = {
            observable: observable$
        };

        observable$.subscribe(rs => {
            delete this.userProjectPermissionsResponse[projectId].observable;
            this.userProjectPermissionsResponse[projectId].data = rs;
        });

        return observable$;
    }
}